//
//  ZDWalletController.m
//  特种车调度
//
//  Created by 陈宇 on 15/8/18.
//
//

#import "ZDWalletController.h"
#import "ZDWalletCell.h"
#import "ZDWalletHeaderView.h"
#import "ZDIncomeDetail.h"
#import "ZDWalletMonth.h"
#import "ZDWalletLog.h"
#import "BMAccountManager.h"

@interface ZDWalletController () <UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong) NSMutableArray *datas;

@property(weak, nonatomic) IBOutlet UILabel *totalLabel;
@property(weak, nonatomic) IBOutlet UILabel *frostLabel;
@property(weak, nonatomic) IBOutlet UIButton *rechargeButton;
@property(weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation ZDWalletController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的钱包";

    [self configuration];

    //    NSURL *url = [[NSBundle mainBundle] URLForResource:@"wallet" withExtension:@"json"];
    //    NSString *json = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    //    NSArray *logs = [ZDWalletLog objectArrayWithKeyValuesArray:json];
    //    [self processData:logs];

    [self loadData];
}

- (void)refreshData
{
    [self.datas removeAllObjects];
    [self loadData];
}

- (void)loadData {
    BMRequest *request = [BMRequest requestWithPath:@"getDispatcherWallet.htm" contentKey:@"walletLogs"];
    request.params = @{@"id" : @([BMAccountManager sharedInstance].user.ID)};
    [self showHudWithhint:kDefaultMessage];
    [ZDWalletLog postWithRequest:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            self.totalLabel.text = [NSString stringWithFormat:@"￥%.2f", [response.rawResult[@"accountBalance"] doubleValue]];
            self.frostLabel.text = [NSString stringWithFormat:@"￥%.2f", [response.rawResult[@"frozenBalance"] doubleValue]];
            [self processData:response.result];
        } else {
            [self showHint:response.msg];
        }
    }];
}

- (void)processData:(NSArray *)data {
    if (data.count == 0)
        return;

    NSMutableArray *array = [NSMutableArray array];
    [data enumerateObjectsUsingBlock:^(ZDWalletLog *obj, NSUInteger idx, BOOL *stop) {
        if ([obj.name isEqualToString:[array.lastObject name]]) {
            [[array.lastObject incomeDetails] addObject:obj];
        } else {
            ZDWalletMonth *month = [ZDWalletMonth new];
            month.name = obj.name;
            month.incomeDetails = [NSMutableArray array];
            [month.incomeDetails addObject:obj];
            [array addObject:month];
        }
    }];

    self.datas = array;
    [self.tableView reloadData];
}

- (void)configuration {
    [self.rechargeButton setBackgroundImage:[UIImage imageWithColor:kGlobalColor] forState:UIControlStateNormal];
    self.rechargeButton.layer.cornerRadius = 16.f;
    self.rechargeButton.layer.masksToBounds = YES;

    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 36.f)];
    bgView.backgroundColor = [UIColor clearColor];
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:14.f];
    label.textColor = kGlobalColor;
    label.text = @"收支明细";
    [bgView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(bgView);
        make.left.mas_equalTo(bgView).offset(15.f);
    }];
    self.tableView.tableHeaderView = bgView;

    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 60.f;
    [self.tableView registerClass:[ZDWalletHeaderView class] forHeaderFooterViewReuseIdentifier:@"reuseHeaderIdentifier"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZDWalletCell" bundle:nil] forCellReuseIdentifier:reuseIdentifier];
    self.tableView.tableFooterView = [UIView new];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    ZDWalletMonth *month = _datas[section];
    if (month.selected) {
        return [_datas[section] incomeDetails].count;
    } else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 34.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    static NSString *reuseHeaderIdentifier = @"reuseHeaderIdentifier";
    weakSelf(self);
    ZDWalletHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:reuseHeaderIdentifier];
    headerView.month = _datas[section];
    headerView.clickAction = ^{
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
    };
    return headerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZDWalletCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    cell.log = [_datas[indexPath.section] incomeDetails][indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ZDIncomeDetail *detail = [_datas[indexPath.section] incomeDetails][indexPath.row];
    detail.selected = !detail.selected;
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

@end
